/**
 * NeuroSky脑波数据服务
 * 
 * 用途：整合蓝牙连接、数据解析、数据收集和API发送功能的核心服务类
 * 方法：协调各个组件的工作，提供统一的接口给上层调用
 * 原理：作为门面模式的实现，封装复杂的蓝牙数据处理流程，对外提供简单易用的API
 */
package com.example.brain_wave.bluetooth

import android.content.Context
import com.example.brain_wave.bluetooth.api.ApiClient
import com.example.brain_wave.bluetooth.collector.DataCollector
import com.example.brain_wave.bluetooth.cache.DataCacheManager
import com.example.brain_wave.bluetooth.session.SessionManager
import com.example.brain_wave.bluetooth.session.SessionState
import com.example.brain_wave.bluetooth.api.SessionResponse
import com.example.brain_wave.bluetooth.model.NeuroSkyRawData
import com.example.brain_wave.bluetooth.model.TabletBrainWaveData
import com.example.brain_wave.api.model.TabletBrainWaveResponse
import kotlinx.coroutines.*

class NeuroSkyService(private val context: Context) {
    
    // 核心组件
    private val bluetoothManager = NeuroSkyBluetoothManager(context)
    private val dataCollector = DataCollector()
    private val apiClient = ApiClient(context)
    private val dataCacheManager = DataCacheManager(context)
    private val sessionManager = SessionManager(context)
    
    // 服务状态
    private var isRunning = false
    
    // 会话创建相关状态
    private var currentSessionState: SessionState = SessionState.IDLE
    private var pendingRoomId: String = ""
    private var pendingUserId: String? = null
    private var isSessionCreationRequested = false  // 防止重复创建会话的标志
    
    // 状态回调
    private var onConnectionStateChanged: ((Boolean) -> Unit)? = null
    private var onDataSent: ((String) -> Unit)? = null
    private var onError: ((String) -> Unit)? = null
    // 新增：服务端数据更新回调
    private var onServerDataUpdated: ((List<TabletBrainWaveResponse>) -> Unit)? = null
    // 新增：会话状态变化回调
    private var onSessionStateChanged: ((SessionState, SessionResponse?) -> Unit)? = null
    // 新增：原始数据接收回调
    private var onRawDataReceived: ((NeuroSkyRawData) -> Unit)? = null
    
    init {
        setupComponents()
    }
    
    /**
     * 设置组件之间的连接
     */
    private fun setupComponents() {
        // 蓝牙连接状态变化
        bluetoothManager.setOnConnectionStateChanged { isConnected ->
            onConnectionStateChanged?.invoke(isConnected)
            if (isConnected) {
                dataCollector.startCollection()
            } else {
                dataCollector.stopCollection()
            }
        }
        
        // 蓝牙数据接收
        bluetoothManager.setOnDataReceived { rawData ->
            // 将数据传递给数据收集器
            dataCollector.addRawData(rawData)
            
            // 调用原始数据接收回调
            onRawDataReceived?.invoke(rawData)
            
            // 只在需要创建会话时才进行检查和日志输出
            // 如果会话已经是ACTIVE状态，就不需要再检查创建条件了
            if (currentSessionState != SessionState.ACTIVE) {
                // 只在IDLE或CONNECTING状态下才尝试创建会话
                if ((currentSessionState == SessionState.IDLE || currentSessionState == SessionState.CONNECTING) 
                    && pendingRoomId.isNotEmpty() 
                    && !isSessionCreationRequested) {
                    println("NeuroSkyService: 检测到数据接收，开始创建会话 - roomId: $pendingRoomId")
                    try {
                        // 设置标志，防止重复创建
                        isSessionCreationRequested = true
                        sessionManager.startNewSession(pendingRoomId, pendingUserId)
                    } catch (e: Exception) {
                        println("NeuroSkyService: 会话创建失败: ${e.message}")
                        // 创建失败时重置标志，允许重试
                        isSessionCreationRequested = false
                    }
                }
            }
        }
        
        // 数据收集完成，准备发送
        dataCollector.setOnDataReady { tabletData ->
            apiClient.sendBrainWaveData(tabletData)
        }
        
        // API发送成功
        apiClient.setOnSuccess { response ->
            onDataSent?.invoke(response)
        }
        
        // API发送失败
        apiClient.setOnError { error ->
            onError?.invoke(error)
        }
        
        // 服务端数据响应处理
        apiClient.setOnServerDataReceived { serverResponse ->
            dataCacheManager.processServerResponse(serverResponse)
        }
        
        // 数据缓存更新
        dataCacheManager.setOnDataUpdated { dataPoints ->
            onServerDataUpdated?.invoke(dataPoints)
        }
        
        // 会话状态变化
        sessionManager.setOnSessionStateChanged { state, session ->
            println("NeuroSkyService: 收到会话状态变化 - 状态: $state, 会话ID: ${session?.id}")
            currentSessionState = state  // 同步会话状态
            
            // 当会话创建成功时，清空待创建的会话信息并重置标志
            if (state == SessionState.ACTIVE && session != null) {
                println("NeuroSkyService: 会话创建成功，清空待创建信息 - pendingRoomId: $pendingRoomId")
                pendingRoomId = ""
                pendingUserId = null
                isSessionCreationRequested = false  // 重置标志
            }
            
            // 会话创建失败或断开时，重置标志允许重新创建
            if (state == SessionState.IDLE || state == SessionState.DISCONNECTED) {
                isSessionCreationRequested = false
            }
            
            onSessionStateChanged?.invoke(state, session)
            println("NeuroSkyService: 会话状态变化回调调用完成")
        }
        
        // 会话管理错误
        sessionManager.setOnError { error ->
            println("NeuroSkyService: 收到会话管理错误 - $error")
            onError?.invoke("会话管理错误: $error")
        }
    }
    
    /**
     * 配置服务参数
     */
    fun configure(
        roomId: String,
        apiBaseUrl: String,
        apiEndpoint: String = "/api/brainwave/data",
        sessionApiBaseUrl: String? = null
    ) {
        println("NeuroSkyService: configure 被调用")
        println("NeuroSkyService: roomId=$roomId, apiBaseUrl=$apiBaseUrl, apiEndpoint=$apiEndpoint, sessionApiBaseUrl=$sessionApiBaseUrl")
        
        dataCollector.setRoomId(roomId)
        // 设置session_id提供者，从SessionManager获取真实的session_id
        dataCollector.setSessionIdProvider { sessionManager.getCurrentSessionId() }
        
        apiClient.setBaseUrl(apiBaseUrl)
        apiClient.setEndpoint(apiEndpoint)
        
        // 配置会话管理器
        if (sessionApiBaseUrl != null) {
            println("NeuroSkyService: 配置SessionManager - sessionApiBaseUrl=$sessionApiBaseUrl")
            sessionManager.configure(sessionApiBaseUrl, dataCacheManager)
            println("NeuroSkyService: SessionManager配置完成")
        } else {
            println("NeuroSkyService: ⚠️ sessionApiBaseUrl为null，跳过SessionManager配置")
        }
        
        println("NeuroSkyService: configure 完成")
    }
    
    /**
     * 连接到NeuroSky设备并开始服务
     */
    suspend fun startService(deviceAddress: String): Boolean {
        if (isRunning) {
            return true
        }
        
        val connected = bluetoothManager.connectToDevice(deviceAddress)
        if (connected) {
            isRunning = true
        }
        return connected
    }
    
    /**
     * 停止服务
     */
    fun stopService() {
        if (!isRunning) {
            return
        }
        
        isRunning = false
        dataCollector.stopCollection()
        bluetoothManager.disconnect()
    }
    
    /**
     * 获取已配对的设备
     */
    fun getPairedDevices() = bluetoothManager.getPairedDevices()
    
    /**
     * 检查蓝牙是否可用
     */
    fun isBluetoothAvailable() = bluetoothManager.isBluetoothAvailable()
    
    /**
     * 获取连接状态
     */
    fun isConnected() = bluetoothManager.isConnected()
    
    /**
     * 获取服务运行状态
     */
    fun isServiceRunning() = isRunning
    
    /**
     * 测试API连接
     */
    suspend fun testApiConnection(): Boolean {
        return apiClient.testConnection()
    }
    
    /**
     * 获取数据缓存大小
     */
    fun getDataBufferSize() = dataCollector.getBufferSize()
    
    /**
     * 获取服务端数据缓存大小
     */
    fun getServerDataCacheSize() = dataCacheManager.getCacheSize()
    
    /**
     * 获取所有缓存的服务端响应
     */
    fun getAllServerResponses() = dataCacheManager.getAllDataPoints()
    
    /**
     * 获取最新的服务端响应
     */
    fun getLatestServerResponse(): TabletBrainWaveResponse? {
        val responses = dataCacheManager.getLatestDataPoints(1)
        return if (responses.isNotEmpty()) responses[0] else null
    }
    
    /**
     * 清空服务端数据缓存
     */
    fun clearServerDataCache() = dataCacheManager.clearCache()
    
    // 回调设置方法
    fun setOnConnectionStateChanged(callback: (Boolean) -> Unit) {
        onConnectionStateChanged = callback
    }
    
    fun setOnDataSent(callback: (String) -> Unit) {
        onDataSent = callback
    }
    
    fun setOnError(callback: (String) -> Unit) {
        onError = callback
    }
    
    fun setOnServerDataUpdated(callback: (List<TabletBrainWaveResponse>) -> Unit) {
        onServerDataUpdated = callback
    }
    
    fun setOnSessionStateChanged(callback: (SessionState, SessionResponse?) -> Unit) {
        onSessionStateChanged = callback
    }
    
    fun setOnRawDataReceived(callback: (NeuroSkyRawData) -> Unit) {
        onRawDataReceived = callback
    }
    
    // 会话管理方法
    
    /**
     * 开始新会话（连接设备按钮功能）
     */
    fun startNewSession(roomId: String, userId: String? = null) {
        println("NeuroSkyService: startNewSession 被调用 - roomId: $roomId, userId: $userId")
        try {
            sessionManager.startNewSession(roomId, userId)
            println("NeuroSkyService: sessionManager.startNewSession 调用完成")
        } catch (e: Exception) {
            println("NeuroSkyService: startNewSession 发生异常: ${e.message}")
            e.printStackTrace()
        }
    }
    
    /**
     * 断开当前会话
     */
    fun disconnectSession() {
        sessionManager.disconnectSession()
    }
    
    /**
     * 获取当前会话状态
     */
    fun getSessionState(): SessionState = sessionManager.getCurrentState()
    
    /**
     * 获取当前会话信息
     */
    fun getCurrentSession(): SessionResponse? = sessionManager.getCurrentSession()
    
    /**
     * 获取当前会话ID
     */
    fun getCurrentSessionId(): String? = sessionManager.getCurrentSessionId()
    
    /**
     * 检查是否有活跃会话
     */
    fun hasActiveSession(): Boolean = sessionManager.hasActiveSession()
    
    /**
     * 测试会话API连接
     */
     suspend fun testSessionApiConnection(): Boolean = sessionManager.testSessionApiConnection()
     
     /**
      * 准备待创建的会话信息（在蓝牙连接前调用）
      */
     fun preparePendingSession(roomId: String, userId: String? = null) {
         println("NeuroSkyService: preparePendingSession - roomId: $roomId, userId: $userId")
         pendingRoomId = roomId
         pendingUserId = userId
         currentSessionState = SessionState.IDLE
     }
 }